window.onload = function () {
    let username = document.getElementById("username");
    let password = document.getElementById("password");
    console.log(username.value);

    username.addEventListener("input", (e) => {
        console.log("正在输入", e.target.value);
    });

    let btn = document.querySelector("button");
    btn.addEventListener("click", (e) => {
        e.preventDefault();

        let name = username.value;
        let key  = password.value;
        let data = { username: name, password: key };

        let promise = new Promise((resolve, reject) => {
            // 把 XHR 移进 executor，才能用 resolve/reject
            let xhr = new XMLHttpRequest();
            xhr.open("POST", "http://127.0.0.1:8080/login", true);   // ← 去掉空格
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    console.log("请求成功了");
                    resolve(xhr.responseText);
                }
            };
            console.log(JSON.stringify(data));
            console.log("开始发送请求");
            xhr.send(JSON.stringify(data));
        });

        promise
            .then((t) => {
                console.log("你输入了正确的name，恭喜你");
                console.log(t);
                setTimeout(() => {
                    location.href = "http://localhost:8080/login"; // ← 去掉空格
                }, 5000);
            })
            .catch((e) => {
                console.log("你输入了错误的name");
                console.log(e);
            })
            .finally(() => {
                console.log("5s之后，页面会跳转");
            });
    });
};